import Vue from "vue";
import Vuex from "vuex";
import { getRequest } from "../utils/api";
import SockJs from "sockjs-client";
import stomp from "stompjs";
import { Notification } from "element-ui";

Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    routes: [],
    sessions: {},
    admins: [],
    currentAdmin: JSON.parse(window.sessionStorage.getItem("user")),
    currentSession: null,
    filterKey: "",
    stomp: null,
    isDot: {}
  },

  // 改变state数据
  mutations: {
    initRoutes(state, data) {
      state.routes = data;
    },
    changecurrentSession(state, id) {
      state.currentSession = id;
      Vue.set(
        state.isDot,
        state.currentAdmin.username + "#" + state.currentSession.username,
        false
      );
    },
    addMessage(state, msg) {
      let mss = state.sessions[state.currentAdmin.username + "#" + msg.to];
      if (!mss) {
        // state.sessions[state.currentAdmin.username + "#" + msg.to] = [];
        Vue.set(state.sessions, state.currentAdmin.username + "#" + msg.to, []);
      }
      state.sessions[state.currentAdmin.username + "#" + msg.to].push({
        content: msg,
        date: new Date(),
        self: !msg.notSelf
      });
    },
    INIT_DATA(state) {
      //浏览器本地历史聊天记录;
      let data = localStorage.getItem("vue-chat-session");
      //console.log(data)
      if (data) {
        state.sessions = JSON.parse(data);
      }
    },
    INIT_ADMINS(state, currentSession) {
      state.admins = currentSession;
    }
  },

  actions: {
    connect(context) {
      context.state.stomp = stomp.over(new SockJs("/ws/ep"));
      let token = window.sessionStorage.getItem("tokenStr");
      token.replace("Bearer", "");
      context.state.stomp.connect(
        { "Auth-Token": token },
        success => {
          console.log(success);
          context.state.stomp.subscribe("/user/queue/chat", msg => {
            let receiveMsg = JSON.parse(msg.body);
            if (
              !context.state.currentSession ||
              receiveMsg.from != context.state.currentSession.username
            ) {
              Notification.info({
                title: "【" + receiveMsg.formNickName + "】发来一条消息",
                message:
                  receiveMsg.content.length > 30
                    ? receiveMsg.content.substr(0, 10)
                    : receiveMsg.content
              });
              Vue.set(
                context.state.isDot,
                context.state.currentAdmin.username + "#" + receiveMsg.from,
                true
              );
            }
            receiveMsg.notSelf = true;
            receiveMsg.to = receiveMsg.from;
            context.commit("addMessage", receiveMsg);
          });
        },
        error => {
          return error;
        }
      );
    },
    //初始化聊天列表
    initData(context) {
      context.commit("INIT_DATA");
      getRequest("/chat/admin").then(resp => {
        if (resp) {
          context.commit("INIT_ADMINS", resp);
        }
      });
    }
  }
});

store.watch(
  function(state) {
    return state.sessions;
  },
  function(val) {
    console.log("CHANGE: ", val);
    localStorage.setItem("vue-chat-session", JSON.stringify(val));
  },
  {
    deep: true /*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
  }
);

export default store;
